// 手动配置路由
/**
 * 准备工作： 1. 安装路由 npm i vue-router
 *           2. 引入vue-router
 *           3. 实例化挂载
 * 4个步骤： 1. 入口(url)
 *          2.  匹配规则
 *          3.  组件
 *          4. 出口
 */
//引入vue
import Vue from 'vue'

//引入路由
import VueRouter from 'vue-router'

//分割方法： const Foo = ()=>import('./Foo.vue) 异步组件

//按需引入子组件
const login = () => import('../components/login/login.vue')
const home = () => import('../components/home/home.vue')
const users = () => import('../components/users/users.vue')
const roles = () => import('../components/roles/roles.vue')
const rights = () => import('../components/rights/rights.vue')
const categories = () => import('../components/categories/categories.vue')
const goods = () => import('../components/goods/goods.vue')
const goodsAdd = () => import('../components/goods-add/goods-add.vue')

//利用vue安装下路由
Vue.use(VueRouter)

// 实例化路由
const router = new VueRouter({
  //匹配路由规则
  routes: [
    //重定向
    { path: '/', redirect: '/login' },
    { path: '/login', component: login },
    {
      path: '/home',
      component: home,
      children: [
        // 动态路由
        { path: '/users/:page?', component: users },
        { path: '/roles', component: roles },
        { path: '/rights', component: rights },
        { path: '/categories', component: categories },
        { path: '/goods', component: goods },
        { path: '/goods-add', component: goodsAdd }
      ]
    }
  ]
})

//通过导航守卫去判断是否有登录过
router.beforeEach((to, from, next) => {
  // console.log(to, from, next)

  // 判断跳转的是否是登录页面,如果是登录页面，允许其直接跳转
  if (to.path === '/login') {
    next()
  } else {
    // 如果不是登录页面，要判断是否有登录过
    let token = localStorage.getItem('token')
    //有值的话，登录过;让其跳转要去的页面;没有值，阻止其跳转，让其跳转到登录页面
    token ? next() : next('/login')
  }
})
//导出路由(main.js需要挂载用)
export default router
